//
//  MyOrderViewController.m
//  EasyToTesco
//
//  Created by mc on 16/2/22.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "MyOrderViewController.h"

#import "HeaderFileForEasyToTesco.h"

#import "MyOrderWholeTableViewCell.h"
#import "FOrderTableViewCell.h"
#import "SVProgressHUD.h"

//选择控制器视图
#import "SelectBtnView.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "ReadLoginData.h"

#import "oilTableViewCell.h"

//orderDetailVC
#import "OrderDetailViewController.h"
#define WIDTH [[UIScreen mainScreen] bounds].size.width
#define NORMWIDTH [[UIScreen mainScreen] bounds].size.width / 375
#define HEIGHT [[UIScreen mainScreen] bounds].size.height
#define NORMHEIGHT [[UIScreen mainScreen] bounds].size.height / 667
#define FRAME [[UIScreen mainScreen] bounds]

@interface MyOrderViewController ()<UITableViewDataSource, UITableViewDelegate, SelectBtnViewDelegate,UIAlertViewDelegate>
{
    NSInteger orderstate;
    BOOL BtnState;
    NSString *usernameStr;
}


@property (nonatomic, strong)NSMutableArray *WholeArray;
@property (nonatomic, strong)NSMutableArray *fOrderArray;
@property (nonatomic, strong)NSMutableArray *OilorderArray;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)NSMutableDictionary *dic;
@property (nonatomic, strong)UITableView *MyOrderTableview;
@property (nonatomic, copy)NSString *userName;
@property (nonatomic, assign)NSInteger i;
@property (nonatomic, strong)NSMutableArray *allArray;

@end

@implementation MyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.i = 0;
    [self getdata];
    [self addMyOrderVcinit];
    [self addMyOrderTopView];
    [self addMyOrderUI];
    [self addMyOrdertableview];
    [SVProgressHUD dismiss];
//
    
}

//菊花
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [SVProgressHUD show];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [SVProgressHUD dismiss];
}

- (void)getdata {
    // 获取当前账号
    NSDictionary *dic = [ReadLoginData readLoginData];
    if (dic.allKeys.count == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录,请登录后再次操作" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alview show];
        
    }else {
        
        usernameStr = [dic[@"data"] objectForKey:@"username"];
        [self MyOrderDataSources];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self dismissViewControllerAnimated:YES completion:nil];

}
- (void)addMyOrderVcinit {
    orderstate = 1000;
    BtnState = YES;
 //   usernameStr = @"13282008515";
    self.WholeArray = [@[]mutableCopy];
    self.fOrderArray = [@[]mutableCopy];
    self.OilorderArray = [@[]mutableCopy];
   self.dic  = [@[]mutableCopy];
    self.allArray = [@[]mutableCopy];

}

- (void)addMyOrderTopView {

    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10*NORMWIDTH, (self.secondView.frame.size.height-20)/2, 20*NORMWIDTH, 20*NORMHEIGHT)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"我的订单";
}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addMyOrdertableview {
    self.MyOrderTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.16, WEITH, HIGHT*0.84) style:UITableViewStyleGrouped];
    self.MyOrderTableview.dataSource = self;
    self.MyOrderTableview.delegate = self;
    self.MyOrderTableview.tableFooterView = [[UIView alloc] init];
    self.MyOrderTableview.rowHeight = 80*NORMHEIGHT;
    [self.view addSubview:self.MyOrderTableview];
}

- (void)addMyOrderUI {
    
    SelectBtnView *selectView =[[SelectBtnView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.06)];

    selectView.delegate = self;

    [self.view addSubview:selectView];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}


#pragma mark -- SelectBtnViewDelegate
-(void)selectBtnClick:(UIButton *)button {
//    NSLog(@"%@----%ld", button.titleLabel.text, button.tag);
   
    orderstate = button.tag;
    
    if (button.tag == 1000) {
        BtnState = YES;
        [self MyOrderDataSources];
    } else if (button.tag == 1001) {
        BtnState = NO;
        [self MyOrderGethfordDataSources];
       
    } else {
        BtnState = NO;
        [self MyOrderGethoilDataSources];
    }
    
    
}

#pragma mark -- UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (BtnState == YES) {
        static NSString *identifier = @"MyOrderWholeTableViewCell";
        MyOrderWholeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"MyOrderWholeTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
//
//       cell.wholeIntrolabel.text = [NSString stringWithFormat:@"%@", [self.dic[@"data"][indexPath.row] objectForKey:@"goodsname"]];
//     cell.wholeValuelabel.text = [NSString stringWithFormat:@"价格：%@", [self.dic[@"data"][indexPath.row] objectForKey:@"zongjia"]];
//        cell.wholeTimelabel.text =[NSString stringWithFormat:@"%@", [self.dic[@"data"][indexPath.row] objectForKey:@"addtime"]];
//        if ([[self.dic[@"data"][indexPath.row] objectForKey:@"zongjia"] isEqualToString:@"1"]) {
//            cell.wholeStatelabel.text  =             [NSString stringWithFormat:@"状态 ： %@",@"已付款"]
//;
//        }else if ([[self.dic[@"data"][indexPath.row] objectForKey:@"zongjia"] isEqualToString:@"2"]){
//            cell.wholeStatelabel.text  =  [NSString stringWithFormat:@"状态 ：%@",@"已退款"];
//        }else{
//               cell.wholeStatelabel.text  =   [NSString stringWithFormat:@"状态 ：%@",@"未付款"];
//           
//            
//        }
//        
//        cell.wholeNumLabel.text = [NSString stringWithFormat:@"收货人：%@", [self.dic[@"data"][indexPath.row] objectForKey:@"shouhuoren"]];
   
        
        
        // all
        cell.wholeIntrolabel.text = [NSString stringWithFormat:@"%@", [self.allArray[indexPath.row] objectForKey:@"goodsname"]];
        cell.wholeValuelabel.text = [NSString stringWithFormat:@"价格：%@", [self.allArray[indexPath.row] objectForKey:@"zongjia"]];
        cell.wholeTimelabel.text =[NSString stringWithFormat:@"%@", [self.allArray[indexPath.row] objectForKey:@"addtime"]];
        if ([[self.allArray[indexPath.row] objectForKey:@"zt"] isEqualToString:@"1"]) {
            cell.wholeStatelabel.text  =             [NSString stringWithFormat:@"状态 ：%@",@"已付款"]
            ;
        }else if ([[self.allArray[indexPath.row] objectForKey:@"zt"] isEqualToString:@"2"]){
#warning 修改状态
            
            cell.wholeStatelabel.text  =  [NSString stringWithFormat:@"状态 ：%@",@"已退款"];
        }else{
            cell.wholeStatelabel.text  =   [NSString stringWithFormat:@"状态 ：%@",@"未付款"];
            
            
        }
        
        cell.wholeNumLabel.text = [NSString stringWithFormat:@"收货人：%@", [self.allArray[indexPath.row] objectForKey:@"shouhuoren"]];
        
        
        
        return cell;
    } else {
        static NSString *identifier = @"FOrderTableViewCell";
        FOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"FOrderTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        
        if (orderstate == 1001) {
            
            cell.ForderCountLabel.text = [NSString stringWithFormat:@"手机号码:%@", [self.fOrderArray[indexPath.row] objectForKey:@"account"]];
            cell.ForderJineLabel.text = [NSString stringWithFormat:@"充值金额:%@", [self.fOrderArray[indexPath.row] objectForKey:@"jine"]];
            cell.Forderfkfslabel.text = [NSString stringWithFormat:@"付款方式:%@", [self.fOrderArray[indexPath.row] objectForKey:@"fkfs"]];

            if ([self.fOrderArray[indexPath.row][@"fkfs"]  isEqualToString:@"1"]) {
                
                cell.Forderfkfslabel.text = [NSString stringWithFormat:@"付款方式:%@",@"充值账户"];
                
            }else{
                   cell.Forderfkfslabel.text = [NSString stringWithFormat:@"付款方式:%@",@"积分账户"];
            }
            
//            NSLog(@"%@", self.fOrderArray[indexPath.row][@"fkfs"]);
            
            
            cell.ForderZtlabel.text = [NSString stringWithFormat:@"充值状态:%@", [self.fOrderArray[indexPath.row] objectForKey:@"zt"]];
            cell.ForderTimeLabel.text = [NSString stringWithFormat:@"充值时间:%@", [self.fOrderArray[indexPath.row] objectForKey:@"addtime"]];
            
            if ([[self.fOrderArray[indexPath.row] objectForKey:@"zt"] isEqualToString:@"1"]) {
                
                 cell.ForderZtlabel.text = [NSString stringWithFormat:@"充值状态:%@", @"成功"];
                
            }else{
                cell.ForderZtlabel.text = [NSString stringWithFormat:@"充值状态:%@", @"失败"];

                
            }
            
        }else{
            
            if ([self.OilorderArray[indexPath.row] objectForKey:@"phoneNo"]) {
                cell.ForderCountLabel.text = [NSString stringWithFormat:@"手机号码:%@", [self.OilorderArray[indexPath.row] objectForKey:@"phoneNo"]];
                cell.ForderJineLabel.text = [NSString stringWithFormat:@"充值金额:%@", [self.OilorderArray[indexPath.row] objectForKey:@"rcMoney"]];
                cell.Forderfkfslabel.text = [NSString stringWithFormat:@"付款方式:%@", [self.OilorderArray[indexPath.row] objectForKey:@"fkfs"]];
                
                if ([self.OilorderArray[indexPath.row][@"fkfs"]  isEqualToString:@"1"]) {
                    
                    cell.Forderfkfslabel.text = [NSString stringWithFormat:@"付款方式:%@",@"充值账户"];
                    
                }else{
                    cell.Forderfkfslabel.text = [NSString stringWithFormat:@"付款方式:%@",@"积分账户"];
                }
                
                //            NSLog(@"%@", self.fOrderArray[indexPath.row][@"fkfs"]);
                
                
                cell.ForderZtlabel.text = [NSString stringWithFormat:@"充值状态:%@", [self.OilorderArray[indexPath.row] objectForKey:@"zt"]];
                cell.ForderTimeLabel.text = [NSString stringWithFormat:@"充值时间:%@", [self.OilorderArray[indexPath.row] objectForKey:@"addtime"]];
                
                if ([[self.OilorderArray[indexPath.row] objectForKey:@"zt"] isEqualToString:@"1"]) {
                    
                    cell.ForderZtlabel.text = [NSString stringWithFormat:@"充值状态:%@", @"成功"];
                    
                }else{
                    cell.ForderZtlabel.text = [NSString stringWithFormat:@"充值状态:%@", @"失败"];
                    
                    
                }

            }
            
        }
     
        return cell;
    }
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (orderstate == 1000) {
        return  self.allArray.count;

    } else if (orderstate == 1001){
        return self.fOrderArray.count;
    } else if (orderstate == 1002){
        return self.OilorderArray.count;
    }else {
        return self.allArray.count;
    }
}



- (void)MyOrderDataSources {
// 商城订单
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

        NSDictionary *dic= @{@"username":usernameStr, @"p":@1};
        [mgr GET:@"http://www.ylgw8.com/AppOrd/getSjList" parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
            self.WholeArray = [self toArrayOrNSDictionary:responseObject];
            self.dic = [self toArrayOrNSDictionary:responseObject];
            self.i = [self.dic[@"data"] count];
            NSLog(@"%@", self.dic);
//            [self.allArray addObject:self.dic[@"data"] ];
            
            
            for (NSDictionary *dica in self.dic[@"data"]) {
                [self.allArray addObject:dica];
            }
            [self MyOrderDataSources2];
//            [self.MyOrderTableview reloadData];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
     //       NSLog(@"%@", error);
        }];
    
    
   
    
}

- (void)MyOrderDataSources2 {
    // 商城订单
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic= @{@"username":usernameStr, @"p":@2};
    [mgr GET:@"http://www.ylgw8.com/AppOrd/getSjList" parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        self.WholeArray = [self toArrayOrNSDictionary:responseObject];
        self.dic = [self toArrayOrNSDictionary:responseObject];
        self.i = [self.dic[@"data"] count];
 //       NSLog(@"%@", self.dic);
//        [self.allArray addObject:self.dic[@"data"]];
        for (NSDictionary *dica in self.dic[@"data"]) {
            [self.allArray addObject:dica];
        }
         [self MyOrderDataSources3];
//        NSLog(@"~~~~%lu", (unsigned long)self.allArray.count);
//        [self.MyOrderTableview reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
     //   NSLog(@"%@", error);
    }];
    
    
   
    
}




- (void)MyOrderDataSources3{
    // 商城订单
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic= @{@"username":usernameStr, @"p":@3};
    [mgr GET:@"http://www.ylgw8.com/AppOrd/getSjList" parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        self.WholeArray = [self toArrayOrNSDictionary:responseObject];
        self.dic = [self toArrayOrNSDictionary:responseObject];
        self.i = [self.dic[@"data"] count];
               NSLog(@"%@", self.dic);
        //        [self.allArray addObject:self.dic[@"data"]];
        for (NSDictionary *dica in self.dic[@"data"]) {
            [self.allArray addObject:dica];
        }
        NSLog(@"~~~~%lu", (unsigned long)self.allArray.count);
        [self.MyOrderTableview reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //   NSLog(@"%@", error);
    }];

}

- (void)MyOrderGethfordDataSources {
  
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
   // NSString *username = @"18620614920";//usernameStr;
    NSString *username = usernameStr;//usernameStr;
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username]};
    
    [mgr POST:@"http://www.ylgw8.com/AppOrd/Gethford" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        NSLog(@"11111111%@",string);
        NSLog(@"11111111%ld",string.length);
        
        if (string.length > 40) {
            self.fOrderArray = [self toArrayOrNSDictionary:responseObject];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"话费暂无数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];

        }

        NSLog(@"fOrderArrayfOrderArray%@", self.fOrderArray);
        [self.MyOrderTableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
         //         NSLog(@"数据请求错误原因:%@", error);
         //         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}

//oilorder
- (void)MyOrderGethoilDataSources {
    
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = usernameStr;
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username]};
    
    [mgr POST:@"http://www.ylgw8.com/AppOrd/Getykord" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
 
        if (string.length > 40) {
            self.OilorderArray = [self toArrayOrNSDictionary:responseObject];

        } else {
            NSLog(@"meiyoushuju ");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"话费暂无数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];

        }
        
        [self.MyOrderTableview reloadData];

    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
         //                  NSLog(@"error:%@", error);
         //                  NSLog(@"errorcode:%ld", (long)operation.response.statusCode);
     }];
    
   }


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{

        // 解析错误
        return nil;
    }
}


@end
